<template>
    <div >
      <n-card title="服务保障" header>
        <div class="header" >
          <div>
            <NButton type="primary" @click="onClickAdd">
              添加服务保障
            </NButton>
          </div>
          <div>
            <n-input-group>
                <n-input v-model:value="params.keyword" clearable placeholder="请输入商品分类关键词" :style="{ width: '100%' }" />
                <n-button @click="categoryList" type="primary" ghost>
                  搜索
                </n-button>
              </n-input-group>
          </div>
        </div>
      </n-card>
      <div class="box" :style="'height:'+innerHeights">
         <!-- 数据表 -->
        <div class="table-box">
       
            <n-data-table
              :loading="messageParams.loading"
              :columns="columns"
              :data="data"
            >
              <!-- <template #expandable-content="{ row, index }">
                
                <div>
                  {{ row.children && row.children.map(child => child.name).join(', ') }}
                </div>
              </template> -->
  
              <template #expandable="{ row, expand }">
                 
                <n-button @click="toggleExpand(row)">{{ expand ? '折叠' : '展开' }}</n-button>
              </template>
            </n-data-table>
       
        </div> 
      </div>
          <div class="pagination">
              <div>共{{pagination.total}}条数据</div>
              <div>
                <n-pagination
                :page="params.pageNum"
                :page-size="params.pageSize"
                :item-count="pagination.total"
                size="medium"
                show-size-picker
                :page-slot="8"
                :page-sizes="pageSizes"
                :on-update:page="pageNext"
                :on-update:page-size="sizeNext"
              />
              </div>
          </div>
  
     <n-modal  v-model:show="showModal"
        :mask-closable="false"
        preset="dialog"
        :title="popTitle"
        content="你确认?"
        positive-text="确认"
        negative-text="算了"
        style="width: 600px;"
        @positive-click="submitCallback"
        @negative-click="cancelCallback"
        >
        <div class="box-modal">
           <n-form
            ref="formRef"
            :model="formValue"
            :rules="rules"
          >
            <n-form-item  label="保障服务条款" path="title">
              <n-input v-model:value="formValue.title" placeholder="请输入保障服务条款" />
            </n-form-item>
            <n-form-item label="内容描述" path="details">
              <n-input v-model:value="formValue.details" placeholder="请输入内容描述" />
            </n-form-item>
        
       
            <n-form-item label="图标（100 * 100)" path="icon">
              <div @click="uploadShow=true" v-if="formValue.icon" style="height:135px;width:100px;overflow: hidden;display: flex;padding:12px;
                  justify-content: center; align-items: center;">
                  <n-image
                  :preview-disabled="true"
                  style="object-fit: contain;display: flex;
                      justify-content: center;
                      align-items: center;"
                  :src="Https()+formValue.icon"/>
              </div>
               <div v-else @click="uploadShow=true" class="imageUpload">
                <n-icon size="24" color="rgb(49, 108, 114)">
                  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 16 16"><g fill="none"><path d="M8 2.5a.5.5 0 0 0-1 0V7H2.5a.5.5 0 0 0 0 1H7v4.5a.5.5 0 0 0 1 0V8h4.5a.5.5 0 0 0 0-1H8V2.5z" fill="currentColor"></path></g></svg>
                </n-icon>
              </div>
              <!-- <n-input v-model:value="formValue.image" placeholder="请输入商品分类图片" /> -->
            </n-form-item>

            <n-form-item label="排序">
              <n-input v-model:value="formValue.sort" placeholder="请输入排序" />
            </n-form-item>
            <n-form-item label="状态" path="status">
              <n-switch 
              @update:value="handleUpdateValue"
              v-model:value="formValue.status">
                <template #checked>
                  启动
                </template>
                <template #unchecked>
                  禁用
              </template>
              </n-switch>
            </n-form-item>
          </n-form>
        </div>
    </n-modal>
  
    <n-modal  v-model:show="uploadShow"
        :mask-closable="false"
        preset="dialog"
        style="width: 1000px;"
        :title="'文件管理'"
        content="你确认?"
        positive-text="确定"
        negative-text="关闭"      
        @positive-click="uploadShow=false"
        @negative-click="uploadShow=false"
        >
        <div class="box-upload">
           <Upload type="1" @selectImage="selectImageFun"/>
        </div>
    </n-modal>
      
    </div>
  </template>
  
  <script setup lang="ts">
  import { NAvatar, NButton, NImage, NSwitch, NTag  } from 'naive-ui'
  import type { FormInst } from 'naive-ui'
  import { nextTick, onMounted, ref } from 'vue'
  import { Https,setPagination,goodsTypeOptions } from "@/utils"
  import api from './api'
  import Upload from "@/views/upload/index.vue"
  // const router = useRouter()
  const innerHeights = ref(0);
  onMounted(() => {
    innerHeights.value = String(window.innerHeight - 280)+'px'
    categoryList()
    // getOptions()
  })
  
  function handleUpdateValue(value: string) {
      if(value){
        formValue.value.status = true
        $message.success("启用")
      }else{
        $message.error("禁用")
        formValue.value.status = false
      }
      
    }
  
  const pageSizes = [
    {
      label: '10 每页',
      value: 10
    },
    {
      label: '20 每页',
      value: 20
    },
    {
      label: '30 每页',
      value: 30
    },
    {
      label: '40 每页',
      value: 40
    }
  ]
  
  
  const pagination = ref({
    total:10
    
  })
  const formRef = ref<FormInst | null>(null);
  
  const showModal = ref(false);
  const uploadShow = ref(false);
  const popTitle = ref('添加商品分类');
  const params = ref({
    pageNum: 1,
    pageSize: 10,
    keyword: '',
  })
  const messageParams: any = ref({
    show: false,
    status: '403',
    loading: true,
  })
  
  const messageList: any = ref([
    {
      status: '500',
      title: '500 服务器错误',
      description: '服务器出错可能说明该雇更多程序员了',
      button: '散财消灾',
    },
    {
      status: '404',
      title: '404 资源不存在',
      description: '生活总归带点荒谬',
      button: '找点乐子吧',
    },
    {
      status: '403',
      title: '403 禁止访问',
      description: '总有些门是对你关闭的',
      button: '放轻松',
    },
  ])
  
  const formValue = ref({
    title:"",
    sort:0,
    details:"",
    icon:"",
    status:true,
  })
  
  const rules = {
  
    title: {
      required: true,
      message: '请输入保障服务名',
      trigger: ['input']
    },
    details: {
      required: false,
      message: '请输入描述',
      trigger: ['input']
    },
  
    icon: {
      required:false,
      message: '请上传商品分类图片(支持url链接)',
      trigger: ['input']
    },
    // status: {
    //   required: true,
    //   message: '状态',
    //   trigger: ['input','image']
    // }
  }
   
  const columns = [
     
    {
      title: 'ID',
      key: 'id',
       
    },
    {
      title: '保障服务条款',
      key: 'title',
      // width: 200,
      ellipsis: true,
    },
    {
      title: '描述',
      key: 'details',
    },
    {
      title: '图片',
      render: ({ icon }) => {
        // console.log(image)
        return h(NImage, {
          width: 60,
          src: Https()+icon,
        })
      },
  
    },
    {
      title: '排序',
      key: 'sort',
    },
    {
      title: '状态',
      render: ({ status }) => {
        // console.log(image)
        return status?'启用':'禁用'
      },
  
    },
    {
      title: '排序',
      key: 'ctime',
    },
    {
      title: '操作',
      key: 'actions',
      width: 460,
      align: 'right',
      fixed: 'right',
      hideInExcel: true,
      render(row,index) {
        return [
          h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              secondary: true,
              onClick: () => handleOpenRolesSet(row),
            },
            {
              default: () => '编辑',
              icon: () => h('i', { class: 'i-fe:database' }),
            },
          ),
  
          h(
            NButton,
            {
              size: 'small',
              type: 'error',
              style: 'margin-left: 12px;',
              onClick: () => handleDelete(row.id),
            },
            {
              default: () => '删除',
              icon: () => h('i', { class: 'i-material-symbols:delete-outline text-14' }),
            },
          ) 
        
        ]
      },
    },
  
  ]
  const data: any = ref([])
  const dataIndex = ref(0)
  const toggleExpand = (row,index) => { // 控制展开和折叠的方法。
    dataIndex.value = index
    if(row.pid == "0"){
      categoryTow(row,index)
      row.expand = !row.expand; // 假设每个行数据对象有一个 expand 属性来控制展开状态。
    }
    
    if(row.pid != "0"){
      categoryThe(row,index)
    }
    
  };
  async function handleDelete(id){
    const res: any = await api.goodsServiceGuaranteeDelApi({
      id:id
    })
  
    if(res.code == 200){
      categoryList();
      $message.success('删除成功!')
    }else{
      
    }
  
  }
  
  
  
  const handleOpenRolesSet =(item) =>{
    formValue.value = item;
    
    popTitle.value = '编辑';
    showModal.value = true;
  } 
  
  const selectImageFun =(selectImageList) =>{
    formValue.value.icon = selectImageList[0];  // 只获取第一张图
    uploadShow.value =false
  } 
  
  
  async function categoryTow(item,index) {
    try {
      const params = {
        pageNum: 1,
        pageSize: 100,
        type_id:item.id
      }
  
      const res: any = await api.categoryListApi(params)
      if (res.code == 200) {
        data.value[index].children = res.data.list
      }
    
    }
    catch (error) {
      console.error(error)
    }
  }
  
  async function categoryThe(item,index) {
    try {
      const params = {
        pageNum: 1,
        pageSize: 100,
        type_id:item.id
      }
  
      const res: any = await api.categoryListApi(params)
      if (res.code == 200) {
        data.value[dataIndex.value].children[index].children = res.data.list
      }
    
    }
    catch (error) {
      console.error(error)
    }
  }
  
  async function categoryList() {
    try {
      getOptions()
      messageParams.value.loading = true
      
    }
    catch (error) {
      console.error(error)
    }
  }
   
  function onClickAdd(){
    popTitle.value = '添加服务保障'
    showModal.value = true
    formValue.value.title = ''
    formValue.value.icon = ''
    formValue.value.status = true
    formValue.value.details = ''
    formValue.value.sort = 0

     
  }
  async function getOptions() {
    
      const res: any = await api.goodsServiceGuaranteeListApi(params.value)
      if(res.code == 200) {
        // data.value = goodsTypeOptions(res.data.list,res.data.children)

        messageParams.value.loading = false
        pagination.value.total = res.data.total
        data.value = res.data.list
        
      }else {
        messageParams.value.show = false
        messageParams.value.status = '500'
      }
       
  }
  async function submitCallback() {
    messageParams.value.loading = true
    formRef.value?.validate((errors) => {
      if (!errors) {
        if(popTitle.value == '添加服务保障')
          categoryAddFun();
        else
          categoryEditFun();
      }
      else {
        showModal.value = true
        return 
   
      }
    })
  }
  const pid = ref('0')
  async function addChildren(item){
    if(item.grade == 3){
      setHomeType(item)
    }else{
      pid.value = item.pid
      formValue.value.split = ''
      formValue.value.categoryDesc = "";
      formValue.value.categoryName = "";
      formValue.value.pid = item.id;
      formValue.value.icon = "";
      popTitle.value = '子分类添加'
      formValue.value.name = item.categoryName
      showModal.value = true
    }
    
  }
  
  async function setHomeType(item){
  
    const res: any = await api.typeSetDataApi({
      recommend:item.recommend == 1?0:1,
      id:item.id
    })
    
    if(res.code == 200){
      categoryList();
      $message.success('设置成功!')
      messageParams.value.loading = false
    }else{
      $message.error(res.message)
    }
  }
  
  
  async function categoryAddFun(){
    formValue.value.grade = pid.value
    const res: any = await api.goodsServiceGuaranteeAddApi(formValue.value)
    if(res.code == 200){
      categoryList();
      
      $message.success('添加成功!')
      messageParams.value.loading = false
    }else{
      $message.error(res.message)
    }
  }
  
  async function categoryEditFun(){
    console.log(pid.value,formValue.value)
    const res: any = await api.goodsServiceGuaranteeEditApi(formValue.value)
    if(res.code == 200){
      if(formValue.value.pid != '0'){
        
      }else
        categoryList();
        $message.success('编辑成功!')
        messageParams.value.loading = false
    }else{
      $message.error(res.message)
    }
  }
  
  function pageNext(page){
    params.value.pageNum = page
    categoryList();
  }
  function sizeNext(size){
    params.value.pageNum = 1
    params.value.pageSize = size
    categoryList();
  }
  
  
  function cancelCallback() {
    
    categoryList();
    showModal.value = false
  }
  </script>
  
  <style scoped>
   .box {
      height: 75vh;
      overflow-y: auto;
  }
  .table-box{
    padding: 20px;
  }
  .box-modal{
    width: 400px;
    /* height: 350px; */
    /* overflow-y: auto; */
  }
  .pagination{
    display: flex;
    justify-content: right;
    /* height: 60px; */
    gap: 10px;
    align-items: center;
    position: relative;
    top: 20px;
    right: 30px;
  }
  .header{
    display: flex;gap: 10px;
  }
  .box-upload{
    /* width: 1000px; */
    height: 650px;
    width: 100%;
    /* background: white; */
  }
  .imageUpload{
    width:100px;
    height:100px;
    border:1px solid #eee;
    display: flex;
    justify-content: center;
    border-radius: 6px;
    align-items: center;
  }
  .imageUpload:hover{
    border:1px solid rgb(49, 108, 114);
  }
  </style>
  